import { DatePicker } from '@/components/AntdProxy';
import CommonDrawer from '@/components/CommonDrawer';
import { CrudFormLayout } from '@/components/Crud';
import { LineSelect } from '@/components/CustomForm';
import { REQUIRED } from '@/constants/rules';
import request from '@/utils/request';
import { useAsyncEffect } from 'ahooks';
import { Form, message } from 'antd';
import dayjs from 'dayjs';

const Copy = (props) => {
  const { record, onCancel, onOk } = props;
  const [form] = Form.useForm();
  useAsyncEffect(() => {
    if (record) {
      form.setFieldsValue({
        ...record,
        day: record.planDate ? dayjs(record.planDate) : undefined,
        oldLineId: record.lineId,
        oldBackLineId: record.backLineId,
      });
    }
  }, [record]);

  const handleOk = async () => {
    const values = await form.validateFields();
    const url = '/datas/line/task/copy';
    const params = {
      ...values,
      lineTaskId: record.lineTaskId,
      day: values.day ? dayjs(values.day).format('YYYY-MM-DD') : '',
    };
    if (record) {
      params.linePlanId = record?.linePlanId;
    }
    await request({
      url,
      method: 'POST',
      data: params,
    });
    message.success('操作成功');
    onOk?.();
  };

  return (
    <CommonDrawer
      title="复制"
      open={true}
      onClose={onCancel}
      onOk={handleOk}
      afterOpenChange={(visible) => {
        if (!visible) {
          form.resetFields();
        }
      }}
      width={800}
      destroyOnHidden
    >
      <Form form={form} layout="vertical">
        <CrudFormLayout itemMinWidth={250}>
          <Form.Item label="原计划线路" name="oldLineId">
            <LineSelect disabled />
          </Form.Item>
          <Form.Item label="原回货线路" name="oldBackLineId">
            <LineSelect disabled />
          </Form.Item>
          <Form.Item label="新计划线路" name="lineId" rules={[REQUIRED]}>
            <LineSelect />
          </Form.Item>
          <Form.Item label="新回货线路" name="backLineId">
            <LineSelect />
          </Form.Item>
          <Form.Item
            label="日期"
            name="day"
            rules={[REQUIRED]}
            initialValue={dayjs().add(1, 'day')}
          >
            <DatePicker placeholder="请选择日期" />
          </Form.Item>
        </CrudFormLayout>
      </Form>
    </CommonDrawer>
  );
};

export default Copy;
